package com.awesome.livedatademo.livedata;

import androidx.appcompat.app.AppCompatActivity;
import androidx.arch.core.util.Function;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.Transformations;

import android.os.Bundle;

import com.awesome.common.util.log.ShowLogUtil;
import com.awesome.livedatademo.R;

public class SwitchMapActivity extends AppCompatActivity {
    private MutableLiveData<String> mMutableLiveData1;
    private MutableLiveData<String> mMutableLiveData2;
    private MutableLiveData<Boolean> mLiveDataSwitch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_switch_map);
        mMutableLiveData1 = new MutableLiveData<>();
        mMutableLiveData2 = new MutableLiveData<>();
        mLiveDataSwitch = new MutableLiveData<>();
        LiveData transformedLiveData = Transformations.switchMap(mLiveDataSwitch, new Function<Boolean, LiveData<String>>() {
            @Override
            public LiveData<String> apply(Boolean input) {
                ShowLogUtil.info("apply:" + input);
                if (input) {
                    return mMutableLiveData1;
                } else {
                    return mMutableLiveData2;
                }
            }
        });

        // 使用map方法，这里不能转化为String
        transformedLiveData.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                ShowLogUtil.info("onChanged:" + s);
            }
        });
        mLiveDataSwitch.postValue(true);
        mMutableLiveData1.postValue("nice to meet you");
        mMutableLiveData2.postValue("how are you?");
    }
}